package com.heima.user.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserLoginMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserLoginMapper, ApUser> implements ApUserLoginService {

    private final ApUserLoginMapper apUserLoginMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.首先判断是否传入手机号和密码，如果没有则返回异常
        if (StringUtils.isEmpty(loginDto.getPhone()) || StringUtils.isEmpty(loginDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        ApUser apUser = apUserLoginMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));

        //2.其次判断数据库中是否有此用户，如果没有则返回异常
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //3.利用数据库中的密码与  传入的密码加上盐以及md5算法运算后的密码比较
        String apUserPassword = apUser.getPassword();
        String inputPassword = loginDto.getPassword() + apUser.getSalt();
        String inputMd5ps = DigestUtils.md5DigestAsHex(inputPassword.getBytes());

        //4.如果不一样，返回异常
        if (!apUserPassword.equals(inputMd5ps)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //5.封装放回结果
        JSONObject result = new JSONObject();
        apUser.setSalt("");
        apUser.setPassword("");
        result.put("user", apUser);
        result.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
        return ResponseResult.okResult(result);
    }
}
